# -*- coding: utf-8 -*-

class WarehousingEntryController < ApplicationController
  before_filter :employee_authorize
  before_filter :sys_before_log
  before_filter :employee_action_hx
  before_filter :privilege_filter,:except=>[:newEntryFromPurchaseOrder,:editEntryFromPurchaseOrder,:getSaleOrersForPurchaseByIds,:hxListForEntry,:sale_entry_print_header,:sale_entry_print_footer,:sale_entry_print_content]

  def warehousingEntryList
    
  end

  #入库审批列表
  def warehousingEntryAuditList

  end
  
  def entryList

  end
  
  def getAllWarehousingEntries
    conditionsHash = Hash.new
    paramsHash = Hash.new
    paramsHash[:offset] = params[:start].to_i
    paramsHash[:limit] = params[:limit].to_i
    conditionsStr = ''

    if params[:order_number].to_s != ''
      conditionsStr = 'warehousing_entries.seq_number like :order_number'
      conditionsHash[:order_number] = params[:order_number].split(/,/)
    end

    if params[:auditing_status].to_s != '' && params[:auditing_status] != ' '
      if conditionsStr == ''
        conditionsStr = 'auditing_status like :auditing_status'
      else
        conditionsStr = conditionsStr+' AND auditing_status like :auditing_status'
      end
      conditionsHash[:auditing_status] = '%'+params[:auditing_status].to_s+'%'
    end
      
    if params[:vendor_id].to_s != ''
      if conditionsStr == ''
        conditionsStr = 'purchase_orders.vendor_id = :vendor_id'
      else
        conditionsStr = conditionsStr+' AND purchase_orders.vendor_id = :vendor_id'
      end
      conditionsHash[:vendor_id] = params[:vendor_id].to_i
    end

    if params[:begin_date].to_s != ''
      if conditionsStr == ''
        conditionsStr = 'warehousing_entries.action_date >= :begin_date'
      else
        conditionsStr = conditionsStr+' AND warehousing_entries.action_date >= :begin_date'
      end
      conditionsHash[:begin_date] = params[:begin_date].to_date
    end

    if params[:end_date].to_s != ''
      if conditionsStr == ''
        conditionsStr = 'warehousing_entries.action_date <= :end_date'
      else
        conditionsStr = conditionsStr+' AND warehousing_entries.action_date <= :end_date'
      end
      conditionsHash[:end_date] = params[:end_date].to_date
    end

    if params[:purchase_order_number].to_s != ''
      if conditionsStr == ''
        conditionsStr = ' purchase_orders.seq_number in (:purchase_order_number)'
      else
        conditionsStr = conditionsStr+' AND purchase_orders.seq_number in (:purchase_order_number)'
      end
      conditionsHash[:purchase_order_number] = params[:purchase_order_number].split(/,/)
    end

    #显示产品
    if params[:product_id].to_s != ''
      if conditionsStr == ''
        conditionsStr = 'warehousing_entry_details.product_id = :product_id'
      else
        conditionsStr = conditionsStr+' AND warehousing_entry_details.product_id = :product_id'
      end
      conditionsHash[:product_id] = params[:product_id].to_i
    end

    role = Role.find(session[:role_id])
    if role.cross_company == "否"
      if conditionsStr == ''
        conditionsStr = 'warehousing_entries.company_id = :company_id'
      else
        conditionsStr = conditionsStr+' AND warehousing_entries.company_id = :company_id'
      end
      conditionsHash[:company_id] = session[:company_id]
    end

    count = WarehousingEntry.countWarehousingEntries conditionsStr,conditionsHash
    entries = WarehousingEntry.findWarehousingEntries conditionsStr,conditionsHash,paramsHash
    jsonStr="{totalProperty:"+count.to_s+",root:"+entries.to_json(:include=>{:company => {:only => [:id, :name]},:employee=> {:only => [:id, :name]},:department=> {:only => [:id, :name]},:warehouse=> {:only => [:id, :name]},:vendor=> {:only => [:id, :name]},:purchase_order=> {:only => [:id, :order_number,:auditing_status]}})+"}"
    #logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end

  def getWarehousingEntriesByAuditStatus
    conditionsHash = Hash.new
    paramsHash = Hash.new
    paramsHash[:offset] = params[:start].to_i
    paramsHash[:limit] = params[:limit].to_i
    conditionsStr = "warehousing_entries.auditing_status like :auditing_status"
    conditionsHash[:auditing_status] = "%#{Constants::APPLY}%"

    if params[:order_number].to_s != ''
      conditionsStr = 'warehousing_entries.seq_number like :order_number'
      conditionsHash[:order_number] = params[:order_number].split(/,/)
    end

    if params[:vendor_id].to_s != ''
      if conditionsStr == ''
        conditionsStr = 'purchase_orders.vendor_id = :vendor_id'
      else
        conditionsStr = conditionsStr+' AND purchase_orders.vendor_id = :vendor_id'
      end
      conditionsHash[:vendor_id] = params[:vendor_id].to_i
    end

    if params[:begin_date].to_s != ''
      if conditionsStr == ''
        conditionsStr = 'warehousing_entries.action_date >= :begin_date'
      else
        conditionsStr = conditionsStr+' AND warehousing_entries.action_date >= :begin_date'
      end
      conditionsHash[:begin_date] = params[:begin_date].to_date
    end

    if params[:end_date].to_s != ''
      if conditionsStr == ''
        conditionsStr = 'warehousing_entries.action_date <= :end_date'
      else
        conditionsStr = conditionsStr+' AND warehousing_entries.action_date <= :end_date'
      end
      conditionsHash[:end_date] = params[:end_date].to_date
    end

    if params[:purchase_order_number].to_s != ''
      if conditionsStr == ''
        conditionsStr = ' purchase_orders.seq_number in (:purchase_order_number)'
      else
        conditionsStr = conditionsStr+' AND purchase_orders.seq_number in (:purchase_order_number)'
      end
      conditionsHash[:purchase_order_number] = params[:purchase_order_number].split(/,/)
    end

    count = WarehousingEntry.countWarehousingEntries conditionsStr,conditionsHash
    entries = WarehousingEntry.findWarehousingEntries conditionsStr,conditionsHash,paramsHash

    jsonStr="{totalProperty:"+count.to_s+",root:"+entries.to_json(:include=>[:employee,:department,:warehouse,:vendor,:purchase_order])+"}"
    #logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end
  
  def getWarehousingEntryDetailsById
    warehousingEntryDetails = WarehousingEntryDetail.where(warehousing_entry_id:params[:id]).includes([:product,:sale_order])
    jsonStr="{totalProperty:"+warehousingEntryDetails.length.to_s+",root:"+warehousingEntryDetails.to_json(:include=>[:product,:sale_order])+"}"
    #logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end

  #查出属于某个采购单的所有入库单
  def getWarehousingEntriesByPurchaseId
    entries = WarehousingEntry.where(purchase_order_id:params[:id])
    jsonStr="{totalProperty:"+entries.length.to_s+",root:"+entries.to_json(:include=>[:employee,:department,:warehouse,:vendor,:purchase_order])+"}"
    #logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end

  def newEntryFromPurchaseOrder    
    @purchaseOrderId = params[:purchase_order_id]
    @vendorId = params[:vendor_id]
    @vendorName = params[:vendor_name]
  end

  #直接生成入库单，这种情况现在暂时不用。
  def create
    
    data = params[:data]
    
    begin
      paramsHash = Util.paramsPreprocessToHash(params[:data])
      #productHash = paramsHash["products"][0]
      #取得这次入库，到入到哪个库中。
      warehousingEntry = WarehousingEntry.new
      warehousingEntry.company_id = session[:company_id]
      warehousingEntry.department_id = session[:department_id]
      warehousingEntry.employee_id = session[:employee_id]
      warehousingEntry.action_date = paramsHash['action_date']
      warehousingEntry.vendor_id = paramsHash['vendor_id']
      warehousingEntry.warehouse_id = paramsHash['warehouse_id']
      warehousingEntry.purchase_order_id = paramsHash['purchase_order_id']
      warehousingEntry.description = paramsHash['description']
      #warehousingEntry.to_warehouse_id = paramsHash['to_warehouse_id']
      #插入products信息
      productsHashArray = paramsHash["products"]
      productsHashArray.each do |productHash|
        warehousingEntryDetail = WarehousingEntryDetail.new
        warehousingEntryDetail.product_id = productHash["product_id"]
        warehousingEntryDetail.quantity = productHash["quantity"]
        warehousingEntryDetail.unit_price = productHash["unit_price"]
        warehousingEntry.warehousing_entry_details << warehousingEntryDetail

        #把转换的记录，加到结算表中。
        #copy内容到结算表
        productCollection = ProductCollection.new
        productCollection.company_id = warehousingEntry.company_id
        productCollection.department_id = warehousingEntry.department_id
        productCollection.employee_id = warehousingEntry.employee_id
        productCollection.vendor_id = warehousingEntry.vendor_id
        productCollection.amount = warehousingEntry.amount
        productCollection.warehouse_id = warehousingEntry.warehouse_id

        productCollection.product_id = warehousingEntryDetail.product_id
        productCollection.quantity = warehousingEntryDetail.quantity
        productCollection.description =  warehousingEntryDetail.description
        #productCollection.discount = warehousingEntryDetail.discount
        productCollection.unit_price = warehousingEntryDetail.unit_price
        productCollection.unit_amount = warehousingEntryDetail.amount
        productCollection.resource_id =  warehousingEntry.id
        productCollection.resource_type =  WarehousingEntry.name
        productCollection.action_date = warehousingEntry.action_date
        
        productCollection.purchase_order_id =  warehousingEntryDetail.purchase_order_id
        productCollection.sale_order_id =  warehousingEntryDetail.purchase_order.sale_order_id
        productCollection.save!
      end
      warehousingEntry.save!
      info="成功"
      result = "{success:true,info:'#{info}'}"
      render :text=>result, :layout=>false
    rescue Exception => e
      logger.info e
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,e.to_s)
    end
  end

  #更新变更在新科的特殊环境中，更变时可以直接更新到数据库中。不用再次审批
  def update
    paramsHash = Util.paramsPreprocessToHash(params[:data])
    #productHash = paramsHash["products"][0]
    
    warehousingEntry = WarehousingEntry.where("id = ? AND company_id = ? AND is_locked <> 1 AND (auditing_status is null OR auditing_status not like ?)",paramsHash['id'],session[:company_id],'%撤消%').first
    if warehousingEntry.lock_version > paramsHash['lock_version'].to_i
      info="有其它用户在您保存之前编辑过此入库单记录，请从新编辑！"
      result = "{success:true,info:'#{info}'}"
      render :text=>result, :layout=>false and return false
    end
    if warehousingEntry != nil
      WarehousingEntry.transaction do
        #生成历史记录
        warehousingEntryHx = WarehousingEntryHx.new
        warehousingEntryHx.company_id = warehousingEntry.company_id
        warehousingEntryHx.department_id = warehousingEntry.department_id
        warehousingEntryHx.employee_id = warehousingEntry.employee_id
      
        warehousingEntry.company_id = session[:company_id]
        warehousingEntry.department_id = session[:department_id]
        warehousingEntry.employee_id = session[:employee_id]
        warehousingEntry.warehouse_id = paramsHash['warehouse_id']
        warehousingEntry.action_date = paramsHash['action_date']
        warehousingEntry.description = paramsHash['description']

        warehousingEntry.audit_opinion = ''
        warehousingEntry.auditor_id = ''

        warehousingEntry.auditing_status = Constants::PASS_APPLY_EDIT

        #products信息
        productsHashArray = paramsHash["products"]
        #在这里，要作一个增，删，编辑操作，以前台数据为准。
        #首先各取出前台与后台的ID数组
        fgIdArray = Array.new
        productsHashArray.each do |productHash|
          fgIdArray << productHash["id"].to_i
        end

        bgIdArray = Array.new
        warehousingEntryDetails = warehousingEntry.warehousing_entry_details
        warehousingEntryDetails.each do |warehousingEntryDetail|
          bgIdArray << warehousingEntryDetail.id
          #借助此循环，生成历史记录内容
          #变更后，记录变更过程
          warehousingEntryHxDetail = WarehousingEntryHxDetail.new
          warehousingEntryHxDetail.product_id = warehousingEntryDetail.product_id
          warehousingEntryHxDetail.quantity = warehousingEntryDetail.quantity
          warehousingEntryHxDetail.purchase_order_id = warehousingEntryDetail.purchase_order_id
          warehousingEntryHxDetail.sale_order_id = warehousingEntryDetail.sale_order_id
          warehousingEntryHxDetail.amount = warehousingEntryDetail.amount
          warehousingEntryHx.warehousing_entry_hx_details << warehousingEntryHxDetail
        end

        idIntersectionArray = fgIdArray & bgIdArray
        addIdArray = fgIdArray - idIntersectionArray
        delIdArray = bgIdArray - idIntersectionArray
        #得到要删除的产品Id数组
        if !delIdArray.empty?
          productIdArray = Array.new
          saleOrderIdArray = Array.new
          purchaseOrderIdArray = Array.new
          warehousingEntryDetails = WarehousingEntryDetail.where("id in (?)",delIdArray)
          warehousingEntryDetails.each do |warehousingEntryDetail|
            saleOrderIdArray << warehousingEntryDetail.sale_order_id
            purchaseOrderIdArray << warehousingEntryDetail.purchase_order_id
            productIdArray << warehousingEntryDetail.product_id
          end
          WarehousingEntryDetail.delete(delIdArray)
          #删除汇总表中的相关内容
          ProductCollection.delete_all(["resource_type = 'WarehousingEntry' AND sale_order_id in (?) AND purchase_order_id in (?)  AND product_id in (?)  AND resource_id = ?",saleOrderIdArray,purchaseOrderIdArray,productIdArray,warehousingEntry.id])
        end

        #在进行从新整理数据之前，先把销售订单的总金额置“0”
        warehousingEntry.amount = 0

        #生成历史记录
        warehousingEntryHx.warehousing_entry_id = warehousingEntry.id
        warehousingEntryHx.warehouse_id = warehousingEntry.warehouse_id
        warehousingEntryHx.action_date = warehousingEntry.action_date
        warehousingEntryHx.purchase_order_id = warehousingEntry.purchase_order_id
        warehousingEntryHx.seq_number = warehousingEntry.seq_number
        warehousingEntryHx.order_number = warehousingEntry.order_number
        warehousingEntryHx.deal_with_status = warehousingEntry.deal_with_status
        warehousingEntryHx.auditing_status = warehousingEntry.auditing_status
        warehousingEntryHx.auditor_id = warehousingEntry.auditor_id
        warehousingEntryHx.audit_opinion = warehousingEntry.audit_opinion
        warehousingEntryHx.vendor_id = warehousingEntry.vendor_id
      
        productsHashArray.each do |productHash|
          #只有当用户选择的产品不为空时，才有详细订单。
          if productHash["product_id"] !=""
            #没Id说明是新增加的。
            if productHash["id"] != ""
              warehousingEntryDetail = WarehousingEntryDetail.find(productHash["id"].to_i)
              warehousingEntryDetail.quantity = productHash["quantity"] #对于出入库来说其实只有数量为唯一的考量。
              warehousingEntryDetail.description = productHash["description"]              
              #同时把汇总表中的相关记录进行修改
              ProductCollection.where("resource_type = 'WarehousingEntry' AND resource_id = #{warehousingEntry.id} AND sale_order_id = #{warehousingEntryDetail.sale_order_id} AND purchase_order_id = #{warehousingEntryDetail.purchase_order_id} AND is_locked = 0 AND product_id =#{warehousingEntryDetail.product_id}").update_all("warehouse_id = #{warehousingEntry.warehouse_id},quantity = #{warehousingEntryDetail.quantity},sale_order_id=#{productHash["sale_order_id"]},description='#{warehousingEntryDetail.description}'")
              warehousingEntryDetail.sale_order_id = productHash["sale_order_id"] #对于出入库来说其实只有数量为唯一的考量。
              warehousingEntryDetail.save
            end
          end
        end
        
        warehousingEntryHx.amount = warehousingEntry.amount
        warehousingEntryHx.save!
        #检查一下，是否经过修改以后，采购订单的状态发生了变化
        #在这儿对比一下采购修改后，与入库发生的变化，以从新设置采购订单的入库状态。
        diffs = PurchaseOrder.diff_purchase_entry(warehousingEntry.purchase_order_id)
        #不等于0有二种情况，一是采购的多了入库的少了，二是入的多采购的少了。不管如何，入库状态都设置为""
        if diffs.length !=0
          warehousingEntry.purchase_order.store_status = Constants::ENTERING
        elsif diffs.length == 0
          warehousingEntry.purchase_order.store_status = Constants::FINISH_ENTRY
        end
        warehousingEntry.purchase_order.save!
        warehousingEntry.save!
      end
    end

    info="成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  #此方法作了调整，不用进行整单的转换，用户可对采购订单进行调整，然后再保存，即一个销售单可对应多个入库单
  def transformPurchaseIntoEntry
    paramsHash = Util.paramsPreprocessToHash(params[:data])
    
    purchaseOrderId = paramsHash['purchase_order_id']
    warehouseId = paramsHash['warehouse_id']
    
    purchaseOrder =  PurchaseOrder.find(purchaseOrderId)
    if purchaseOrder.store_status == Constants::PASS_APPLY_CANCEL
      info = "已经撤消的采购订单，不可以再转换为入库单！"
    elsif   purchaseOrder.store_status == Constants::FINISH_ENTRY
      info = "已经入库完毕的采购订单，不可以再转换为入库单！"
    else
      
      #开始事务，确保在流水号正常的情况下，保存入库单时,一但出现问题，则循环执行
      begin
        Sequence.transaction do
          warehousingEntry = WarehousingEntry.new
          warehousingEntry.purchase_order_id = purchaseOrder.id
          warehousingEntry.company_id = purchaseOrder.company_id
          warehousingEntry.department_id = purchaseOrder.department_id
          warehousingEntry.employee_id = purchaseOrder.employee_id
          warehousingEntry.action_date = paramsHash['action_date']
          warehousingEntry.vendor_id = purchaseOrder.vendor_id
          warehousingEntry.amount = purchaseOrder.amount
          warehousingEntry.warehouse_id = warehouseId
          warehousingEntry.auditing_status = Constants::PASS_APPLY_ADD
          warehousingEntry.save!  #先行保存一下，以便生成ID
          purchaseOrder.store_status = Constants::ENTERING
          #为了在进行结算表操作时提前获取ID，这时要提前存储purchaseOrder

          #向详细表中插入products信息
          productsHashArray = paramsHash["products"]
          productsHashArray.each do |productHash|
            #如果不为空则加入
            if productHash["product_id"] != ""
              #得到采购订单的详细价格，只有取出它的详细记录来。
              purchaseOrderDetail = PurchaseOrderDetail.find(productHash["id"])
              warehousingEntryDetail = WarehousingEntryDetail.new
              warehousingEntryDetail.sale_order_id = productHash["sale_order_id"]
              warehousingEntryDetail.purchase_order_id = purchaseOrder.id
              warehousingEntryDetail.product_id = productHash["product_id"]
              warehousingEntryDetail.quantity = productHash["quantity"]
              warehousingEntryDetail.unit_price = purchaseOrderDetail.unit_price
              warehousingEntryDetail.discount = purchaseOrderDetail.discount
              warehousingEntryDetail.amount = warehousingEntryDetail.quantity * warehousingEntryDetail.unit_price
              warehousingEntry.amount = warehousingEntry.amount + warehousingEntryDetail.amount #计算订单总金额
              warehousingEntryDetail.description = productHash["description"]
              warehousingEntry.warehousing_entry_details << warehousingEntryDetail

              #同时生成结算表的内容。
              productCollection = ProductCollection.new
              #copy内容到结算表
              #在进行成功转换后，要同时操作结算表，把此次操作的详细内容，完全拆解开，复制到结算表中。
              productCollection.company_id = purchaseOrder.company_id
              productCollection.department_id = purchaseOrder.department_id
              productCollection.employee_id = purchaseOrder.employee_id
              productCollection.vendor_id = purchaseOrder.vendor_id
              #TODO:这儿的总值有问题，要从新处理
              productCollection.amount = purchaseOrder.amount
              productCollection.warehouse_id = warehouseId
              productCollection.product_id = purchaseOrderDetail.product_id
              productCollection.quantity = productHash["quantity"] #purchaseOrderDetail.quantity
              productCollection.discount = purchaseOrderDetail.discount
              productCollection.unit_price = purchaseOrderDetail.unit_price
              productCollection.unit_amount = purchaseOrderDetail.amount
              productCollection.resource_id =  warehousingEntry.id
              productCollection.resource_type =  WarehousingEntry.name

              productCollection.action_date = warehousingEntry.action_date
              productCollection.purchase_order_id =  purchaseOrderDetail.purchase_order_id
              productCollection.sale_order_id =  purchaseOrderDetail.sale_order_id
              productCollection.description =  warehousingEntryDetail.description
              productCollection.save!
            end
          end

          #在这儿再检查，对比一下采购订单与入库单的数量差，以确认要不要添加上“出库完毕”状态
          purchaseOrders = PurchaseOrder.select("pd.id,pd.quantity,pd.product_id,newed.quantity as we_quantity,(sum(pd.quantity) - ifnull(newed.quantity,0)) as balance_quantity").joins("po left join purchase_order_details pd on po.id = pd.purchase_order_id
left join (select warehousing_entry_id,e.purchase_order_id,product_id,sum(quantity) as quantity
from warehousing_entries e left join warehousing_entry_details ed on e.id = ed.warehousing_entry_id
where e.purchase_order_id = "+purchaseOrderId+" AND e.auditing_status != '#{Constants::PASS_APPLY_CANCEL}'
group by product_id) newed on newed.product_id = pd.product_id
left join products p on p.id = pd.product_id
where po.id =  "+purchaseOrderId + " group by pd.product_id having sum(pd.quantity) - ifnull(newed.quantity,0) > 0")
          if purchaseOrders.length == 0
            purchaseOrder.store_status = Constants::FINISH_ENTRY
          end
          #开始为出库单取得流水号
          sequence = Sequence.where("company_id = ? AND sub_type = ?",session[:company_id],WarehousingEntry.name).first

          sequence.seq_no = sequence.seq_no + 1
          warehousingEntry.seq_number = sequence.seq_no
          warehousingEntry.order_number = sequence.ab + ":" + warehousingEntry.seq_number.to_s + ":" + Date.today.to_s
          sequence.save!
          warehousingEntry.save!
          #最后保存采购订单的状态更改。
          purchaseOrder.save!
        end
      rescue ActiveRecord::StaleObjectError
        #这个异常是说明，你当提交时，有人提前更新了你之前读取的信息，违反乐观锁。要retry
        #这里特别指序号产生表。
        logger.info "somebody useing sn before yours.............................................................."
        DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,"StaleObjectError")
        retry
      rescue ActiveRecord::RecordNotFound
        logger.info "RecordNotFound................................................................................"
        DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,"RecordNotFound")
      rescue Exception => e
        logger.info "logging......................................................................................."
        DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,e.to_s)
        logger.info e
      end
      info = "成功"
    end
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  #申请撤消,如果系统设置不需要审批，则直接可以撤消。
  def applyToCancel
    begin
      WarehousingEntry.transaction do
        warehousingEntry = WarehousingEntry.find(params[:id])
        sysParam =  SysParam.find_by_company_id(session[:company_id])
        if sysParam.audit_for_warehousing_entry_cancel == "否"
          warehousingEntry.auditing_status = Constants::PASS_APPLY_CANCEL
          warehousingEntry.deal_with_status = Constants::CANCELED
          ProductCollection.delete_all("resource_type = 'WarehousingEntry' AND resource_id = #{params[:id]}")
          #直接删除
        else
          warehousingEntry.auditing_status = Constants::AUDIT_APPLY_CANCEL
        end
        warehousingEntry.auditor_id = session[:employee_id]
        warehousingEntry.save!
        
        #在这儿对比一下采购修改后，与入库发生的变化，以从新设置采购订单的入库状态。
        diffs = PurchaseOrder.diff_purchase_entry(warehousingEntry.purchase_order_id)
        #不等于0有二种情况，一是采购的多了入库的少了，二是入的多采购的少了。不管如何，入库状态都设置为""
        if diffs.length !=0
          warehousingEntry.purchase_order.store_status = Constants::ENTERING
        elsif diffs.length == 0
          warehousingEntry.purchase_order.store_status = Constants::FINISH_ENTRY
        end
        warehousingEntry.purchase_order.save!        
      end
      
    rescue Exception => e
      info = e.to_s
      logger.info info
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,e.to_s)
    end
    info = "成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  
  #审批新增状态,这个方法还没有起动。要修改成专为入库单操作的方法
  def updateAuditingStatus
    warehousingEntry = WarehousingEntry.find(params[:id])
    info = nil
    if warehousingEntry !=nil
      auditingStatus = params[:auditing_status]
      warehousingEntry.auditor_id = session[:employee_id]
      warehousingEntry.audit_opinion =  params[:audit_opinion]
      if(auditingStatus == "是")
        if warehousingEntry.auditing_status == Constants::AUDIT_APPLY_EDIT
          auditingStatus = Constants::PASS_APPLY_EDIT
        else
          auditingStatus = Constants::PASS_APPLY_ADD
        end
        warehousingEntry.auditing_status = auditingStatus
      else
        if warehousingEntry.auditing_status == Constants::AUDIT_APPLY_EDIT
          auditingStatus = Constants::REJECT_APPLY_EDIT
        else
          auditingStatus = Constants::REJECT_APPLY_ADD
        end
        warehousingEntry.auditing_status = auditingStatus
      end
      warehousingEntry.save!
      #结算表处理完毕。
      info = "成功"
    else
      info = "失败，没有找到相应的销售入库单。"
    end
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  def updateAuditingCancelStatus

  end

  def getWarehousingEntryById
    warehousingEntry = WarehousingEntry.where(id:params[:id]).includes([:vendor]).first
    rootStr = warehousingEntry.to_json(:include=>[:vendor])
    jsonStr = "{root:["+rootStr+"]}"
    #logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end

  #在编辑入库单时，根据当前的入库情况判断可入库数量是多少。
  def getDetailsBalanceByIdForEdit
    entryId = params[:id]
    warehousingEntry = WarehousingEntry.find(entryId)
    warehousingEntryDetails = warehousingEntry.warehousing_entry_details
    #销售详细
    #balance_quantity为当前最大的可入数量。即修改后的数字不能大于balance_quantity
    warehousingEntries = WarehousingEntry.select("ed.id,we.purchase_order_id,pd.sale_order_id,ifnull(so.order_number,'非定向采购') as sale_order_number,p.id as product_id,p.name as product_name,p.is_suit,p.unit_price,p.number,p.spec,p.unit,ed.quantity,ed.discount,ed.amount,ed.description,newed.quantity as ed_quantity,(pd.quantity - ifnull(newed.quantity,0) + ifnull(ed.quantity,0)) as balance_quantity").joins("we left join warehousing_entry_details ed on we.id = ed.warehousing_entry_id
left join (select ed.sale_order_id,warehousing_entry_id,product_id,sum(quantity) as quantity
from warehousing_entries we left join warehousing_entry_details ed on we.id = ed.warehousing_entry_id
where we.purchase_order_id = #{warehousingEntry.purchase_order_id} AND we.auditing_status != '#{Constants::PASS_APPLY_CANCEL}'
group by product_id,ed.sale_order_id) newed on newed.product_id = ed.product_id AND newed.sale_order_id = ed.sale_order_id
left join products p on p.id = ed.product_id
left join purchase_order_details pd on pd.purchase_order_id = we.purchase_order_id and pd.product_id = ed.product_id AND pd.sale_order_id = ed.sale_order_id AND pd.is_locked = 0
left join sale_orders so on so.id = ed.sale_order_id
where we.id =  "+entryId)

    jsonStr="{totalProperty:"+warehousingEntries.length.to_s+",root:"+warehousingEntries.to_json()+"}"
    #logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end

  #得到可供索赔的详细货品种类与数量，已经索赔的会排除在外。这次要针对product_id分组，因为在采购订单中是由销售订单和产品二个参数分组的。
  #此版本的修改是为了显示每个采购订单中的不同的销售订单的单号。不再以产品Id为唯一区分。
  def getDetailBalanceForClaim
    warehousingEntryId = params[:warehousing_entry_id]
    warehousingEntries = WarehousingEntryDetail.select("ed.id,p.id as product_id,p.name as product_name,p.is_suit,p.unit_price,p.number,p.spec,p.unit,sum(ed.quantity) as quantity,sum(ed.amount) as amount,ed.description,newcd.quantity as ed_quantity,(sum(ed.quantity) - ifnull(newcd.quantity,0)) as balance_quantity").joins("ed
left join (select cd.warehousing_entry_id,cd.product_id,sum(cd.quantity) as quantity
from claim_details cd left join claims c on c.id = cd.claim_id
where cd.warehousing_entry_id = "+warehousingEntryId+" AND c.auditing_status != '#{Constants::PASS_APPLY_CANCEL}'
group by product_id) newcd on newcd.product_id = ed.product_id
left join products p on p.id = ed.product_id
where ed.warehousing_entry_id =  "+warehousingEntryId+ " group by ed.product_id having sum(ed.quantity) - ifnull(newcd.quantity,0) > 0")

    jsonStr="{totalProperty:"+warehousingEntries.length.to_s+",root:"+warehousingEntries.to_json()+"}"
    #logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end

  #在编辑入库单时，要得到某采购订单下，某货品下的的可以选择的销售订单,分别传入采购订单Id和产品Id
  def getSaleOrersForPurchaseByIds
    purchaseOrderDetails = PurchaseOrderDetail.select("pd.sale_order_id,ifnull(so.order_number,'非定向采购') as order_number").joins("pd left join sale_orders so on pd.sale_order_id = so.id where pd.purchase_order_id = #{params[:purchase_order_id]} AND pd.product_id = #{params[:product_id]}")
    jsonStr = "{totalProperty:"+purchaseOrderDetails.length.to_s+",root:"+purchaseOrderDetails.to_json()+"}"
    #logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end

  #得到变更历史的摘要
  def getHxesById
    warehousingEntryHxes = WarehousingEntryHx.where(warehousing_entry_id:params[:id]).includes([:department,:employee,:warehouse])
    jsonStr="{totalProperty:"+warehousingEntryHxes.length.to_s+",root:"+warehousingEntryHxes.to_json(:include=>[:department,:employee,:warehouse])+"}"
    #logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end

  #根据变更Id得到详细信息
  def getHxDetailsByHxId
    warehousingEntryHxDetails = WarehousingEntryHxDetail.where(warehousing_entry_hx_id:params[:id]).includes([:product])
    jsonStr="{totalProperty:"+warehousingEntryHxDetails.length.to_s+",root:"+warehousingEntryHxDetails.to_json(:include=>{:product=>{:only=>[:id,:number,:name,:is_suit,:spec]}})+"}"
    #logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end

  #生成打印销售凭证的头部
  def sale_entry_print_header
    @warehousingEntry = WarehousingEntry.find(params[:id],:include=>[:warehouse,:purchase_order,:vendor])
    @purchaseOrder = @warehousingEntry.purchase_order
  end

  #生成打印销售凭证的内容
  def sale_entry_print_content
    @warehousingEntry = WarehousingEntry.find(params[:id],:include=>[:warehousing_entry_details,:purchase_order,:vendor,:warehouse])
    @warehousingEntryDetails = @warehousingEntry.warehousing_entry_details
    @totalQuantity = @warehousingEntryDetails.sum(:quantity)
    logger.info @totalQuantity
  end

  def sale_entry_print_footer
    @warehousingEntry = WarehousingEntry.find(params[:id],:include=>[:warehousing_entry_details,:purchase_order,:vendor,:warehouse])
  end
end